//
//  LYNavigationController.m
//  LYDevelopKit
//
//  Created by 李阳 on 2018/5/25.
//

#import "LYNavigationController.h"

@interface LYNavigationController ()
<UINavigationControllerDelegate>
/// 手势代理
@property (nonatomic, strong)id popDelegate;
@end

@implementation LYNavigationController


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _popDelegate = self.interactivePopGestureRecognizer.delegate;
    self.delegate = self;
    _hiddenBottomBarWhenPushed = YES;
    _popGestureEnable = YES;
}


- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (self.viewControllers.count)
    {
        viewController.hidesBottomBarWhenPushed = self.hiddenBottomBarWhenPushed;
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        !_backButtonConfigBlockWhenPush ?: _backButtonConfigBlockWhenPush(btn, viewController);
        
        [btn addTarget:viewController action:@selector(backNavigationItemDidClick) forControlEvents:UIControlEventTouchUpInside];
        viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:btn];
    }
    
    [super pushViewController:viewController animated:animated];
}

- (void)navigationController:(UINavigationController *)navigationController
       didShowViewController:(UIViewController *)viewController
                    animated:(BOOL)animated {
    if ([self.viewControllers indexOfObject:viewController] == 0)
    {
        //根控制器
        //还原滑动返回手势代理
        self.interactivePopGestureRecognizer.delegate = _popDelegate;
    }
    else
    {
        //实现滑动返回功能
        //清空滑动返回手势代理，就能实现滑动返回功能
        self.interactivePopGestureRecognizer.delegate = nil;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)respondsToSelector:(SEL)aSelector
{
    if (aSelector == @selector(navigationController:didShowViewController:animated:))
    {
        return _popGestureEnable;
    }
    return [[self class] instancesRespondToSelector:aSelector];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end



@implementation UIViewController (LYNavigationController)


/// 点击导航控制器返回按钮，子类可重写
- (void)backNavigationItemDidClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
